/**
 * 文件上传组件
 */

import React, { useState, useCallback, useRef } from 'react';
import {
  Upload,
  X,
  AlertTriangle,
} from 'lucide-react';
import { useDocument } from '@/contexts/document';
import { showMessage } from '@/components/common/MessageTip';
import FileTypeIcon from './FileTypeIcon';

interface FileUploaderProps {
  isOpen: boolean;
  onClose: () => void;
  className?: string;
}

interface UploadFile {
  file: File;
  id: string;
  progress: number;
  status: 'pending' | 'uploading' | 'success' | 'error';
  error?: string | null;
}

// 支持的文件类型
const SUPPORTED_TYPES = [
  // 文档
  '.pdf', '.doc', '.docx', '.txt', '.md', '.rtf',
  // 表格
  '.xls', '.xlsx', '.ods',
  // 演示
  '.ppt', '.pptx', '.odp',
  // 图片
  '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg',
  // 压缩
  '.zip', '.rar', '.7z', '.tar', '.gz'
];

const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

// 获取文件扩展名
function getFileExtension(filename: string): string {
  return filename.toLowerCase().substring(filename.lastIndexOf('.'));
}

// 验证文件
function validateFile(file: File): string | null {
  const extension = getFileExtension(file.name);
  
  if (!SUPPORTED_TYPES.includes(extension)) {
    return `不支持的文件类型: ${extension}`;
  }
  
  if (file.size > MAX_FILE_SIZE) {
    return `文件大小超过限制 (最大 50MB)`;
  }
  
  return null;
}

export default function FileUploader({ isOpen, onClose, className = '' }: FileUploaderProps) {
  const { 
    categories,
    loading,
    uploadDocument
  } = useDocument();
  const [uploadFiles, setUploadFiles] = useState<UploadFile[]>([]);
  const [isDragOver, setIsDragOver] = useState(false);
  const [uploadForm, setUploadForm] = useState({
    title: '',
    description: '',
    categoryId: '',
    tags: [] as string[],
  });
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 重置状态
  const resetState = useCallback(() => {
    setUploadFiles([]);
    setUploadForm({
      title: '',
      description: '',
      categoryId: '',
      tags: [],
    });
  }, []);

  // 关闭弹窗
  const handleClose = useCallback(() => {
    resetState();
    onClose();
  }, [resetState, onClose]);

  // 添加文件
  const addFiles = useCallback((files: FileList) => {
    const newFiles: UploadFile[] = [];
    
    Array.from(files).forEach(file => {
      const error = validateFile(file);
      newFiles.push({
        file,
        id: `${file.name}-${Date.now()}-${Math.random()}`,
        progress: 0,
        status: error ? 'error' : 'pending',
        error,
      });
    });
    
    setUploadFiles(prev => [...prev, ...newFiles]);
  }, []);

  // 文件选择处理
  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      addFiles(e.target.files);
    }
  }, [addFiles]);

  // 拖拽处理
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      addFiles(e.dataTransfer.files);
    }
  }, [addFiles]);

  // 移除文件
  const removeFile = useCallback((fileId: string) => {
    setUploadFiles(prev => prev.filter(f => f.id !== fileId));
  }, []);

  // 上传单个文件
  const uploadSingleFile = useCallback(async (uploadFile: UploadFile) => {
    try {
      // 更新状态为上传中
      setUploadFiles(prev => prev.map(f => 
        f.id === uploadFile.id ? { ...f, status: 'uploading', progress: 0 } : f
      ));

      // 创建FormData
      const formData = new FormData();
      formData.append('file', uploadFile.file);
      formData.append('title', uploadForm.title || uploadFile.file.name);
      if (uploadForm.description) {
        formData.append('description', uploadForm.description);
      }
      if (uploadForm.categoryId) {
        formData.append('category_id', uploadForm.categoryId);
      }
      uploadForm.tags.forEach(tag => {
        formData.append('tags', tag);
      });

      // 上传文件
      const document = await uploadDocument(formData);

      // 更新状态为成功
      setUploadFiles(prev => prev.map(f => 
        f.id === uploadFile.id ? { ...f, status: 'success', progress: 100 } : f
      ));

      // 添加到文档列表
      // 上传成功后刷新文档列表
      
      return document;
    } catch (error) {
      // 更新状态为失败
      setUploadFiles(prev => prev.map(f => 
        f.id === uploadFile.id ? { 
          ...f, 
          status: 'error', 
          error: error instanceof Error ? error.message : '上传失败' 
        } : f
      ));
      throw error;
    }
  }, [uploadForm, uploadDocument]);

  // 开始上传
  const handleUpload = useCallback(async () => {
    const pendingFiles = uploadFiles.filter(f => f.status === 'pending');
    
    if (pendingFiles.length === 0) {
      showMessage('warning', '没有可上传的文件');
      return;
    }

    // 开始上传

    try {
      // 并发上传文件
      const uploadPromises = pendingFiles.map(uploadSingleFile);
      const results = await Promise.allSettled(uploadPromises);
      
      const successCount = results.filter(r => r.status === 'fulfilled').length;
      const failCount = results.filter(r => r.status === 'rejected').length;
      
      if (successCount > 0) {
        showMessage('success', `成功上传 ${successCount} 个文件`);
      }
      
      if (failCount > 0) {
        showMessage('error', `${failCount} 个文件上传失败`);
      }
      
      // 如果全部成功，关闭弹窗
      if (failCount === 0) {
        setTimeout(handleClose, 1000);
      }
    } catch (error) {
      showMessage('error', '上传过程中发生错误');
      console.error('Upload error:', error);
    }
  }, [uploadFiles, uploadSingleFile, handleClose]);

  // 重试上传
  const retryUpload = useCallback((fileId: string) => {
    const file = uploadFiles.find(f => f.id === fileId);
    if (file && file.status === 'error') {
      uploadSingleFile(file);
    }
  }, [uploadFiles, uploadSingleFile]);

  if (!isOpen) return null;

  return (
    <div className={`fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 ${className}`}>
      <div className="bg-card rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-border">
          <h2 className="text-lg font-semibold text-foreground">上传文档</h2>
          <button
            onClick={handleClose}
            className="w-8 h-8 flex items-center justify-center rounded hover:bg-accent transition-colors"
          >
            <X className="w-5 h-5 text-muted-foreground" />
          </button>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* 文件上传区域 */}
          <div
            className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
              isDragOver
                ? 'border-primary bg-primary/10'
                : 'border-border hover:border-input'
            }`}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
          >
            <Upload className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-medium text-foreground mb-2">
              拖拽文件到此处或点击选择
            </h3>
            <p className="text-sm text-muted-foreground mb-4">
              支持 PDF、Word、Excel、PPT、图片、压缩包等格式，最大 50MB
            </p>
            <button
              onClick={() => fileInputRef.current?.click()}
              className="px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary-hover transition-colors"
            >
              选择文件
            </button>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept={SUPPORTED_TYPES.join(',')}
              onChange={handleFileSelect}
              className="hidden"
            />
          </div>

          {/* 文件列表 */}
          {uploadFiles.length > 0 && (
            <div className="mt-6">
              <h3 className="text-sm font-medium text-foreground mb-3">
                待上传文件 ({uploadFiles.length})
              </h3>
              <div className="space-y-3 max-h-48 overflow-y-auto">
                {uploadFiles.map(uploadFile => (
                  <div
                    key={uploadFile.id}
                    className="flex items-center space-x-3 p-3 bg-muted rounded-lg"
                  >
                    <FileTypeIcon 
                      fileType={getFileExtension(uploadFile.file.name).slice(1)} 
                      size="md" 
                    />
                    
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-foreground truncate">
                        {uploadFile.file.name}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {(uploadFile.file.size / 1024 / 1024).toFixed(2)} MB
                      </p>
                      
                      {/* 进度条 */}
                      {uploadFile.status === 'uploading' && (
                        <div className="mt-2">
                          <div className="w-full bg-accent rounded-full h-1.5">
                            <div
                              className="bg-primary h-1.5 rounded-full transition-all duration-300"
                              style={{ width: `${uploadFile.progress}%` }}
                            />
                          </div>
                        </div>
                      )}
                      
                      {/* 错误信息 */}
                      {uploadFile.status === 'error' && uploadFile.error && (
                        <div className="flex items-center mt-1">
                          <AlertTriangle className="w-3 h-3 text-destructive mr-1" />
                          <p className="text-xs text-destructive">{uploadFile.error}</p>
                        </div>
                      )}
                    </div>

                    {/* 状态图标和操作 */}
                    <div className="flex items-center space-x-2">
                      {uploadFile.status === 'pending' && (
                        <span className="text-xs text-muted-foreground">待上传</span>
                      )}
                      {uploadFile.status === 'uploading' && (
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary" />
                      )}
                      {uploadFile.status === 'success' && (
                        <span className="text-xs text-[hsl(var(--tag-active-bg))]">✓ 成功</span>
                      )}
                      {uploadFile.status === 'error' && (
                        <button
                          onClick={() => retryUpload(uploadFile.id)}
                          className="text-xs text-primary hover:text-primary-hover underline"
                        >
                          重试
                        </button>
                      )}
                      
                      <button
                        onClick={() => removeFile(uploadFile.id)}
                        className="w-5 h-5 flex items-center justify-center rounded hover:bg-accent transition-colors"
                      >
                        <X className="w-3 h-3 text-muted-foreground" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 上传配置 */}
          {uploadFiles.length > 0 && (
            <div className="mt-6 space-y-4">
              <h3 className="text-sm font-medium text-foreground">上传配置</h3>
              
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  文档标题
                </label>
                <input
                  type="text"
                  value={uploadForm.title}
                  onChange={(e) => setUploadForm({ ...uploadForm, title: e.target.value })}
                  placeholder="留空将使用文件名"
                  className="w-full border border-input rounded-lg px-3 py-2 text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  文档描述
                </label>
                <textarea
                  value={uploadForm.description}
                  onChange={(e) => setUploadForm({ ...uploadForm, description: e.target.value })}
                  rows={2}
                  placeholder="可选"
                  className="w-full border border-input rounded-lg px-3 py-2 text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  分类
                </label>
                <select
                  value={uploadForm.categoryId}
                  onChange={(e) => setUploadForm({ ...uploadForm, categoryId: e.target.value })}
                  className="w-full border border-input rounded-lg px-3 py-2 text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                >
                  <option value="">选择分类（可选）</option>
                  {categories.map((category: any) => (
                    <option key={category.id} value={category.id}>
                      {category.icon} {category.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          )}
        </div>

        {/* 底部操作 */}
        {uploadFiles.length > 0 && (
          <div className="flex items-center justify-between p-6 border-t border-border">
            <div className="text-sm text-muted-foreground">
              共 {uploadFiles.length} 个文件，
              {uploadFiles.filter(f => f.status === 'success').length} 个已上传
            </div>
            <div className="flex items-center space-x-3">
              <button
                onClick={handleClose}
                className="px-4 py-2 text-sm border border-input text-foreground rounded-lg hover:bg-accent transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleUpload}
                disabled={loading.uploading || uploadFiles.filter(f => f.status === 'pending').length === 0}
                className="px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {loading.uploading ? '上传中...' : '开始上传'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
